/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ik.servlets;

import com.ik.pbs.Encapsulados.PerfilUsuario;
import com.ik.pbs.Manejadores.ManejadorPerfilUsuario;
import com.ik.pbs.Manejadores.ManejadorUsuarios;
import com.ik.pbs.conection.ConexionDB;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Malkavian
 */
@WebServlet(name = "subirImagen", urlPatterns = {"/subirImagen"})
public class subirImagen extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ConexionDB con = new ConexionDB();
        File file = null;
        FileItem item = null;
        String fieldName = "";
        String fileName = "";
//        String test = request.getParameter("usu");
//        System.out.println(test);
        int error = 2;
        try {

            int maxFileSize = 5000 * 1024;
            int maxMemSize = 5000 * 1024;
            ServletContext context = getServletContext();
            String fullPath = "";
            String filePath = context.getRealPath("") + "\\Recursos\\images\\user\\";
            String usuario = "";

            // Verify the content type
            String contentType = request.getContentType();
            if ((contentType.indexOf("multipart/form-data") >= 0)) {

                DiskFileItemFactory factory = new DiskFileItemFactory();
                // maximum size that will be stored in memory
                factory.setSizeThreshold(maxMemSize);
                // Location to save data that is larger than maxMemSize.
                factory.setRepository(new File("c:\\temp"));

                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                // maximum file size to be uploaded.
                upload.setSizeMax(maxFileSize);
                try {
                    // Parse the request to get file items.
                    List fileItems = upload.parseRequest(request);

                    // Process the uploaded file items
                    Iterator i = fileItems.iterator();
                    if (i.hasNext()) {
                        while (i.hasNext()) {
                            FileItem fi = (FileItem) i.next();

                            if (!fi.isFormField() && !fi.getName().isEmpty()) {
                                // Get the uploaded file parameters
                                fieldName = fi.getFieldName();
                                fileName = fi.getName();
                                boolean isInMemory = fi.isInMemory();
                                item = fi;
                                long sizeInBytes = fi.getSize();
                                


                            } else {
                                if (fi.getFieldName().equals("usu")) {
                                    usuario = fi.getString();
                                }
                            }
                        }
                    } else {
                        error = 2;
                    }
                } catch (Exception ex) {
                    System.out.println(ex);
                    if (file != null) {
                        file.deleteOnExit();
                    }

                    error = 2;
                }

                PerfilUsuario perfil = ManejadorPerfilUsuario.getInstance().getPerfilUsuario(con.getConnectionDB(), Integer.parseInt(usuario));

                if (perfil != null && !fileName.isEmpty()) {
                    // Write the file
                    if (fileName.lastIndexOf("\\") >= 0) {
                        file = new File(filePath
                                + usuario + "_" + fileName.substring(fileName.lastIndexOf("\\")));
                        fullPath = usuario + "_" + fileName.substring(fileName.lastIndexOf("\\"));
                    } else {
                        file = new File(filePath
                                + usuario + "_" + fileName.substring(fileName.lastIndexOf("\\") + 1));
                        fullPath = usuario + "_" + fileName.substring(fileName.lastIndexOf("\\") + 1);
                    }
                    
                    perfil.setFoto("/PBS/Recursos/images/user/" + fullPath);

                    if (ManejadorPerfilUsuario.getInstance().actualizarPerfilUsuario(con.getConnectionDB(), perfil)) {

                        // if (!file.exists()) {
                        item.write(file);
                        //    } else {
                        ////        error = 3;
                        //   }
                        error = 1;
                    } else {
                        error = 2;
                    }

                } else {
                    error = 2;
                }


            } else {
                error = 2;
            }
            
            response.sendRedirect("/PBS/"+ManejadorUsuarios.getInstance().getUsuario(con.getConnectionDB(), Integer.parseInt(usuario)).getPerfil().getNombre().toLowerCase()+"/avatar.jsp?error=" + error);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            error = 2;
            response.sendRedirect("/PBS/"+ManejadorUsuarios.getInstance().getUsuario(con.getConnectionDB(), Integer.parseInt(request.getParameter("usu"))).getPerfil().getNombre().toLowerCase()+"/avatar.jsp?error=" + error);
        } finally {
            try {
                con.getConnectionDB().close();
                out.close();
            } catch (SQLException ex) {
                Logger.getLogger(subirImagen.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
